package cn.marinda.config;

import cn.marinda.MinecraftServerHelper;
import cn.marinda.entity.Server;
import cn.marinda.entity.ServerInfo;
import cn.marinda.util.FileUtils;
import cn.marinda.util.ServerUtils;
import cn.marinda.util.ThreadUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 抽象服务器配置
 *
 * @author admin
 * @date 2022/07/25
 */
public abstract  class AbstractServerConfiguration implements ServerConfiguration {

    protected File file;
    protected Map<String,Object> configMap = new HashMap<>();
    protected ServerInfo serverInfo;
    protected List<String> list = new ArrayList<>();
    /**
     * 单选框属性映射 & 文本框属性映射
     */
    protected Map<String,Boolean> selectPropertiesMap = new HashMap<>();
    protected Map<String,String> settingPropertiesMap = new HashMap<>();
    /**
     * 抽象服务器配置
     */
    public AbstractServerConfiguration(){

    }

    /**
     * 抽象服务器配置
     *
     * @param file 文件
     */
    public AbstractServerConfiguration(File file){
        this.file = file;
        serverInfo = MinecraftServerHelper.serverInfo;
    }

    /**
     * 读配置文件
     *
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public void readFileConfig(){
        this.configMap = serverInfo.readServerFileConfig(file);
    }

    /**
     * 将ConfigMap数据写入回文件配置
     */
    public void writeFileConfig(){
        try {
            StringBuilder sb = new StringBuilder();
            FileOutputStream outputStream = new FileOutputStream(file);
            for(String key : configMap.keySet()){
                Object value = configMap.get(key);
                String formatStr = String.format("%s=%s",key,value.toString());
                outputStream.write(formatStr.getBytes(StandardCharsets.UTF_8));
                outputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
            }
            outputStream.flush();
            outputStream.close();
            ServerUtils.writeServerPropertiesFlag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /**
     * 绑定选择属性映射
     *
     * @param selectPropertiesMap 选择属性映射
     */
    public void bindSelectPropertiesMap(Map<String,Boolean> selectPropertiesMap){
        this.selectPropertiesMap = selectPropertiesMap;
    }

    /**
     * 绑定设置属性映射
     *
     * @param settingPropertiesMap 设置属性映射
     */
    public void bindSettingPropertiesMap(Map<String,String> settingPropertiesMap){
        this.settingPropertiesMap = settingPropertiesMap;
    }





}
